import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/element/general/HomeView.vue'
import axios from "/src/Axios/axios";
import FingerprintJS from '@fingerprintjs/fingerprintjs';

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'home',
        component: HomeView
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/element/general/LoginView.vue')
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('../views/element/general/RegisterView.vue')
    },
    {
        path: '/homePage',
        name: 'homePage',
        component: () => import('../views/element/user/UserHomePageView.vue')
    },
    {
        path: '/admin',
        name: 'admin',
        component: () => import('@/components/MenuLayOut.vue'),
        children: [
            {
                path: '/adminHomePage',
                name: 'adminHomePage',
                meta: {title: '管理员首页'},
                component: () => import('@/views/element/admin/systemConfiguration/AdminHomePageView.vue')
            },
            {
                path: '/userManage',
                name: 'userManage',
                meta: {title: '用户管理'},
                component: () => import('@/views/element/admin/userManage/UserManageView.vue')
            },
            {
                path: '/homePageImgSet',
                name: 'homePageImgSet',
                meta: {title: '首页图片配置'},
                component: () => import('@/views/element/admin/systemConfiguration/HomePageImgSetView.vue')
            },
            {
                path: '/billTypeManage',
                name: 'billTypeManage',
                meta: {title: '记账类型配置'},
                component: () => import('@/views/element/admin/systemConfiguration/BillTypeManageView.vue')
            },
            {
                path: '/materialLibrary',
                name: 'materialLibrary',
                meta: {title: '素材库配置'},
                component: () => import('@/views/element/admin/systemConfiguration/MaterialLibraryView.vue')
            },
        ]
    },
    {
        path: '/user',
        name: 'user',
        component: () => import('@/components/MenuLayOut.vue'),
        children: [
            {
                path: '/userHomePage',
                name: 'userHomePage',
                meta: {title: '用户首页'},
                component: () => import('@/views/element/user/UserHomePageView.vue')
            },
            {
                path: '/personalHomePage',
                name: 'personalHomePage',
                component: () => import('../views/element/general/PersonalHomePageView.vue')
            },
            {
                path: '/bill',
                name: 'bill',
                component: () => import('../views/element/user/BillView.vue')
            },
        ]
    },
]
const router = new VueRouter({
    mode: 'hash',
    routes
})
router.beforeEach(async (to, from, next) => {

    if (!routeExists(to.name)) {
        Vue.prototype.$message({
            message: '页面不存在！！！',
            type: 'error'
        });
        setTimeout(() => {
            next('/');
        }, 1500);
        console.log('页面不存在');
        return;
    }
    // 检查是否存在token
    const token = sessionStorage.getItem('token');
    let flag = sessionStorage.getItem('flag') === '1'
    if (to.path !== '/login' && to.path !== '/register' && to.path !== '/' && !token && !flag) {
        if (!token) {
            const fp = await FingerprintJS.load();
            const result = await fp.get();
            let fingerprint = result.visitorId;
            axios.get('/system/checkToken/'+fingerprint).then(res => {
                if (res.code === 200) {
                    if(res.data!=null) {
                        sessionStorage.setItem('token', res.data.token);
                        sessionStorage.setItem('identity', res.data.identity);
                        if (res.data.identity === 0) {
                            next('/userHomePage');
                        } else {
                            next('/adminHomePage');
                        }
                    }
                } else if (res.code === 401) {
                    Vue.prototype.$message({
                        message: '未登录',
                        type: 'warning'
                    });
                    setTimeout(() => {
                        next('/');
                    }, 1500);

                } else if (res.code === 403) {
                    Vue.prototype.$message({
                        message: '身份信息已过期，请重新登录',
                        type: 'warning'
                    });
                    setTimeout(() => {
                        next('/');
                    }, 1500);

                }else if (res.code === 402) {
                    console.log('请先登录')
                    alert('请先登录')
                    this.window.location.reload()
                }else{
                    next('/');
                }
            }).catch(() => {
               window.location.reload()
            }).finally(() => {
                sessionStorage.setItem('flag', '1');
            })
        }
    } else {
        next();
    }
})

// 辅助函数：检查路由是否存在
function routeExists(routeName) {
    const routes = router.options.routes;
    let flag = false;
    routes.forEach(route => {
        if (route.name === routeName) {
            flag = true;
        }
        if (route.children && route.children.length > 0) {
            route.children.forEach(child => {
                if (child.name === routeName) {
                    flag = true;
                }
            });
        }
    });
    return flag;
}

//修复Router3.0版本之后，push方法报错问题
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}
export default router
